<template>
  <div class="meterage-manage-detail">
    <el-dialog width="70%" :visible.sync="formShow" @close="handleClickDeal('cancel')" v-dialog-drag class="image-progress-detail" append-to-body :modal-append-to-body="false" :close-on-click-modal="false">
      <span slot="title">
        <i class="iconfont icon-zhiliangguanli1"></i>
        <span>{{title}}</span>
      </span>
      <el-tabs v-model="activeName" v-show="detailType!=='build'&&detailType!=='edit'">
        <el-tab-pane label="基本信息" name="first"></el-tab-pane>
        <el-tab-pane label="审批记录" name="second" v-if="detailType!=='build'"></el-tab-pane>
      </el-tabs>
      <div class="WholeScroll" style="max-height: 650px; overflow: auto;padding: 0 15px;">
        <cmsDetailRowFile v-show="activeName == 'first'&&detailType!='build'" :tableFileList="formBaseData.fileList" :showTable="showRowTable"></cmsDetailRowFile>
        <el-form :model="formBaseData" class="" ref="formBaseData" v-show="activeName == 'first'" :rules="formBaseRules" v-loading="isLoading">
          <el-row>
            <div class="content-box">
              <div class="left-box WholeScroll">
                <p :class="{ active: activeIndex == item.id }" @click="changeTab(item.id)" v-for="(item, index) in tabs" :key="index">{{ item.name }}</p>
              </div>
              <div class="right-box WholeScroll">
                <!-- 督办内容 -->
                <!-- <el-form :model="formBaseData" ref="formBaseData" :rules="formBaseRules"> -->
                <!--检查内容 -->
                <div v-if="activeIndex == 0">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="监督检查类型" :label-width="formlabelWidth1" prop="inspectionType">
                        <el-select class="select" size="small" v-model="formBaseData.inspectionType" placeholder="选择类型" clearable :disabled="['check','approve'].indexOf(detailType)!==-1">
                          <el-option v-for="item in inspectionTypeArr" :key="item.id" :label="item.name" :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="建设单位" :label-width="formlabelWidth1" prop="companyId">
                        <el-select class="select" size="small" v-model="formBaseData.companyId" placeholder="选择类型" clearable :disabled="['check','approve'].indexOf(detailType)!==-1">
                          <el-option v-for="item in companylist" :key="item.id" :label="item.name" :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="受检单位" :label-width="formlabelWidth1" prop="buildUnitId">
                        <el-select class="select" size="small" v-model="formBaseData.buildUnitId" placeholder="选择受检单位" clearable :disabled="['check','approve'].indexOf(detailType)!==-1">
                          <el-option v-for="item in inspectedCompanyList" :key="item.id" :label="item.name" :value="item.id">
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="检查主要内容" :label-width="formlabelWidth1" prop="checkContent">
                        <el-input size="small" type="textarea" v-model="formBaseData.checkContent" placeholder="请输入检查主要内容" :disabled="['check','approve'].indexOf(detailType)!==-1" :rows="4"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="检查中查出的问题" :label-width="formlabelWidth1" prop="problems">
                        <el-input size="small" type="textarea" v-model="formBaseData.problems" placeholder="请输入检查中查出的问题" :disabled="['check','approve'].indexOf(detailType)!==-1" :rows="4"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="检查处理意见" :label-width="formlabelWidth1" prop="handlingSuggestion">
                        <el-input size="small" type="textarea" v-model="formBaseData.handlingSuggestion" placeholder="请输入检查处理意见" :disabled="['check','approve'].indexOf(detailType)!==-1" :rows="4"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="签发时间" :label-width="formlabelWidth1" prop="issueTime">
                        <el-date-picker style="width:100%;" v-model="formBaseData.issueTime" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" :disabled="['check','approve'].indexOf(detailType)!==-1" format="yyyy-MM-dd">
                          ></el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="检查人员" :label-width="formlabelWidth1" required>
                        <cmsPopoverTree :defaultProps="defaultProps" ref="cmsPopoverTree" :data="linkUserOpts" :selectVal="checkedLinkUsers" type="multi" @addMulTag="addMulTag" :defaultIds="defaultIds" @delTag="delTag" @addTag="addTag" :disabled="['check','approve'].indexOf(detailType)!==-1" />
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="整改期限" :label-width="formlabelWidth1" prop="rectificationPeriod">
                        <el-date-picker style="width:100%;" v-model="formBaseData.rectificationPeriod" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" :disabled="['check','approve'].indexOf(detailType)!==-1" format="yyyy-MM-dd">
                          ></el-date-picker>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row>
                    <el-col :sapn="12">
                      <el-form-item label="附件" :label-width="formlabelWidth1">
                        <cmsUploadFile ref="fileTwo" :detail-id="detailBaseId" :fileSystem="fileSystem['two']" :fileList="fileList1" :disabled="['check','approve'].indexOf(detailType)!==-1" type="mul" info="支持上传 png/jpg/gif/doc/xlsx/ppt/pdf 文件" :detail-type="detailType" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
                <!--  -->
                <div v-if="activeIndex == 2">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="整改完成日期" :label-width="formlabelWidth1" prop="completionTime">
                        <el-date-picker style="width:100%;" v-model="formBaseData.completionTime" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="选择日期" :disabled="detailType == 'check'||formBaseData.zghf ">
                          ></el-date-picker>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="项目名称" :label-width="formlabelWidth1" prop="projectSection">
                        <el-input size="small" v-model="formBaseData.projectSection" :disabled="detailType === 'check'||formBaseData.zghf"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="责任单位" :label-width="formlabelWidth1" prop="accountabilityUnit">
                        <el-input size="small" v-model="formBaseData.accountabilityUnit" :disabled="detailType === 'check'||formBaseData.zghf"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item label="整改结果" :label-width="formlabelWidth1" prop="rectificationResult">
                        <el-input class="fill" type="textarea" :autosize="{ minRows: 4, maxRows: 6}" placeholder="" v-model="formBaseData.rectificationResult" :disabled="detailType === 'check'||formBaseData.zghf"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-form-item label="附件" :label-width="formlabelWidth1" prop="proimg">
                      <cmsUploadFile ref="fileOne" :detail-id="detailBaseId" :fileSystem="fileSystem['one']" :fileList="fileList" :disabled="detailType === 'check'|| detailType === 'audit'||formBaseData.zghf" type="mul" info="支持上传 png/jpg/gif/doc/xlsx/ppt/pdf 文件" :detail-type="detailType" />
                    </el-form-item>
                  </el-row>
                </div>
                <!-- </el-form> -->
              </div>
            </div>
          </el-row>

          <el-row style="margin-top: 15px">
            <el-col :span="24">
              <bpmn-form v-if="isShowBpmn" ref="bpmnForm" proc-def-key="supervisionCheckProcess" :business-id="formBaseData.id" :url="url" :entity="formBaseData" :formlabelWidth="formlabelWidth" @complete="onComplete" :needInit="false" :variables="variables"></bpmn-form>
            </el-col>
          </el-row>
        </el-form>
        <el-tab-pane label="审批记录" name="second" v-show="activeName == 'second'&&formBaseData.procInstId">
          <wf-process :inst-id="formBaseData.procInstId" :url="urlProcess" />
        </el-tab-pane>
      </div>
      <div slot="footer" class="dialog-footer">
        <pop-btn ref="btn" :key="formShow" proc-def-key="supervisionCheckProcess" :business-id="formBaseData.id" :readonly="readonly" :task-id="formBaseData.taskId" @save="onSave" @approve="onApprove" @apply="onApply" @cancel="cancel" />
      </div>
    </el-dialog>

  </div>
</template>

<script>
//  复制粘贴改下面的名字
import projectSectionInfo, { getAllCompanyTree } from '@/api/buss/common'
import WfProcess from '@/components/WorkFlow/process/index'
import msgUtil from '@/utils/msgUtil'
import startMixin from '@/mixins/wfStartMixin'
import approveMixin from '@/mixins/wfApproveMixin'
import PopBtn from '@/components/ExtBpmn/Btn/index'
import BpmnForm from '@/components/ExtBpmn/ExtForm/bpmn-form'
import sectionInfo from '@/api/buss/sectionInfo'
import crudDict from '@/api/system/dict'
import cmsTableChoose from '@/components/cms/cmsTableChoose'
import dept from "@/api/system/dept";
import supervisionCheck from "@/api/buss/supervisionCheck";
import cmsPopoverTree from "@/views/components/cmsPopoverTree";
import { getAll as getRoles, getRoleByUserId } from "@/api/system/role";
export default {
  name: `safe-patrol-manage-detail`,
  components: {
    WfProcess,
    BpmnForm,
    PopBtn,
    cmsPopoverTree,
    cmsTableChoose
  },
  mixins: [startMixin, approveMixin],
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {}
      }
    }
  },
  watch: {
    postDetail(value) {
      console.log("type=", value.type)
      // if (value.type != 'check') {}
      // 显示详情弹窗
      this.formShow = value.show
      // 初始化窗口参数
      this.activeName = 'first'
      // 详情类型
      this.detailType = value.type
      this.title = value.typeName
      this.search = value.search
      this.formBaseData.sectionId = value.search && value.search.sectionId
      this.formBaseData.sectionName = value.search && value.search.sectionName
      this.formBaseData.projectId = value.search && value.search.projectId
      this.formBaseData.projectName = value.search && value.search.projectName
      // 详情id
      this.detailBaseId = value.detailId ? value.detailId : ''
      this.isShowBpmn = true
      this.user = this.$store.getters.user
      this.$nextTick(() => {
        if (this.detailType !== 'build') {
          // this.initData()
          // 获取详情请求
          this.getDetail()
        } else {
          let arr = [
            { name: '检查内容', id: 0 }
          ]
          this.$set(this, 'tabs', arr)
          // this.initData()
          this.initBtn()
          this.getCompanyBySectionId(this.formBaseData.sectionId)//受检单位
        }
        this.getDict()
        this.getApplyCompany()//公司数
        this.getAllCompanyTree()//建设单位
      })
    },
  },
  data() {
    return {
      user: '',
      treeProps: { children: 'children' },
      activeCollapse: ['1', '2'],
      activeCollapseTwo: ['3'],
      activeCollapseThree: ['4'],
      contractListTable: [],
      checkRowKeys: [],
      showContractListDialog: false,
      showAreaSelectDialog: false,
      chooseRow: {},
      checkQuestionTypeArr: {},
      worksCategoryArr: {},
      passArr: [{
        name: '通过',
        id: '1'
      }, {
        name: '不通过',
        id: '2'
      }],
      areaList: [],
      pickerOptions0: {
        disabledDate: (time) => {
          if (time.getTime() > Date.now() - 8.64e6) {
            return true
          }
        }
      },
      selectedIds: [],
      activeIndex: 0,
      tabs: [{ name: '检查内容', id: 0 }],
      isShowBpmn: false,
      detailBaseId: '',
      readonly: false,
      variables: { principal: 3 },
      entity: {},
      checkInitShow: false,
      companyTree: [], // 公司下拉
      projectTree: [], // 项目下拉
      sectionTree: [], // 标段下拉
      planNameArr: [], //获取计划名称
      wfNode: {},
      url: 'buss/supervisionCheck/node/attribute',
      urlProcess: 'buss/supervisionCheck/process',
      title: '',
      search: {},
      isLoading: false,
      vm: this,
      //dialog宽度
      dialogColumn: '2',
      //存放对应按钮数量的文件list
      fileListArray: [],
      fileListArray2: [],
      inspectionLevelList: [],
      urgencyList: [],
      secondTableData: [],
      formBaseData: {
        projectId: '',
        projectName: '',
        sectionName: '',
        sectionId: '',
        inspectionType: '',
        companyId: '',
        buildUnit: '',
        buildUnitId: '',
        checkContent: '',
        problems: '',
        handlingSuggestion: '',
        //-----------------------------------------------
        issueTime: '',
        inspector: '2',
        rectificationPeriod: '',
        completionTime: '',
        projectSection: '',
        accountabilityUnit: '',
        rectificationResult: '',
        zghf: true,
        zgys: true,
      },
      file1: [],
      file2: [],
      dict: { rectifications: [{ label: '限期整改', value: '1' }, { label: '否', value: '2' }] },
      //  被选中的用于新增的项目
      showSelectDialog: false,
      detailType: 'build', // 详情类型 build新建 check不可编辑查看 edit编辑
      isAudit: '',
      detailId: '', // 当前详情的id
      activeName: 'first', //
      detailActions: [], // 当前详情的操作项
      formShow: false, // 表单展示
      formlabelWidth1: '120px',
      formlabelWidth: '165px', // 表单左侧标题宽度
      //  当前操作数据的所属合同号
      contractId: null,
      fileSystem: {
        'one': {
          sys: 'buss',
          module: 'supervision',
          part: 'one',
          compoName: 'fileOne'
        },
        'two': {
          sys: 'buss',
          module: 'supervision',
          part: 'two',
          compoName: 'fileTwo'
        }
      },
      fileList: [],
      fileList1: [],
      treePopover: false,
      treeList: [],
      defaultCheckArr: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showPickerObj: {
        show: false
      },
      defaultIds: [],
      linkUsers: {},
      ownerRepresentativeUsers: {},
      linkUserOpts: [],
      checkedLinkUsers: [],
      formBaseRules: {
        inspectionType: [
          { required: true, message: '请选择监督检查类型', trigger: 'change' }
        ],
        companyId: [
          { required: true, message: '请选择建设单位', trigger: 'change' }
        ],
        buildUnitId: [
          { required: true, message: '请选择受检单位', trigger: 'change' }
        ],
        checkContent: [
          { required: true, message: '请输入检查主要内容', trigger: 'blur' }
        ],
        problems: [
          { required: true, message: '请输入检查中查出的问题', trigger: 'blur' }
        ],
        handlingSuggestion: [
          { required: true, message: '请输入检查处理意见', trigger: 'blur' }
        ],
        issueTime: [
          { required: true, message: '请选择签发时间', trigger: 'change' }
        ],
        rectificationPeriod: [
          { required: true, message: '请选择整改期限', trigger: 'change' }
        ],
        completionTime: [
          { required: true, message: '请选择整改完成日期', trigger: 'change' }
        ],
        projectSection: [{ required: true, message: '请填写项目名称', trigger: 'blur' }],
        accountabilityUnit: [{ required: true, message: '请填写责任单位', trigger: 'blur' }],
        rectificationResult: [{ required: true, message: '请填写整改结果', trigger: 'blur' }],
        proimg: [{ require: true, message: '请上传附件' }]
      }, // 表单基本信息验证
      meterageManageDetail: '',
      /**
       * 审批配置数据
       * */
      auditConfigData: {
        //  实体基本数据
        baseData: {},
        //  基本请求地址
        urlBase: '',
        //  是否显示
        show: false,
        //  提交数据成功时候的回调函数
        submitCallBack: null,
        //  选择了动作时的回调函数
        selActionCallBack: null
      },
      //  显示审批提交按钮
      showAuditBtn: false,
      selectTreeChildren: [],
      taskDefKey: '',
      entityId: '',
      buildUnitTable: [],
      buildUnitTableTwo: [],
      buildUnitTableThree: [],
      tableLong: 0,
      isNeedInit: false,
      vxeTableCheckData: [],
      matherData: [],
      inspectionTypeArr: [],
      companylist: [
        // { name: '测试', id: '1' }
      ],
      inspectedCompanyList: [
        // { name: '测试', id: '1' }
      ],
      checkerList: [
        // { name: '测试人员', id: '' }
      ],
    }
  },

  created() {
    this.getDict()
    // this.initUserInfo()
  },
  methods: {
    resetCheck() {
      this.$refs.addTree.setCheckedKeys([])
      this.$set(this, 'defaultCheckArr', [])
    },
    initUserInfo() {
      if (this.detailType == 'build') {
        var user = JSON.parse(localStorage.getItem('sysUser'))
        this.formBaseData.inspector = user.name
        this.formBaseData.checkUnit = user.companyName
      }
    },
    //整改回复
    getZghf() {
      let sysUser = JSON.parse(localStorage.getItem('sysUser'))
      this.formBaseData.headRectification = sysUser.name
      if (this.formBaseData.taskKey) {
        // 原有条件：UserTask_1n69yep、UserTask_1i38bv8
        // 新增条件：UserTask_1sci9cl:施工单位节点
        if (['UserTask_1sci9cl', 'UserTask_1n69yep', 'UserTask_1i38bv8'].indexOf(this.formBaseData.taskKey) !== -1) {//可编辑状态
          this.formBaseData.zghf = false
        } else {
          this.formBaseData.zghf = true
        }
      } else {
        this.formBaseData.zghf = true
      }
    },
    //整改验收
    getZgys() {
      if (this.formBaseData.taskKey) {
        if (this.formBaseData.taskKey == 'UserTask_0yhw2t4' || this.formBaseData.taskKey == 'UserTask_1jcbnu6') {
          this.formBaseData.zgys = false
        } else {
          this.formBaseData.zgys = true
        }
      } else {
        this.formBaseData.zgys = true
      }

    },
    cantRename() {
      //不可编辑的条件
      let flag = false
      if (this.detailType == 'check' || this.detailType == 'approve') {
        flag = true
      }
      if (this.detailType == 'check') {
        flag = true
      }
      return flag

    },
    cantRename2() {
      //不可编辑的条件
      //cantRename 为 true 为不可编辑
      let flag = false

      if (this.formBaseData.taskKey != 'UserTask_1i38bv8' && this.formBaseData.taskKey != 'UserTask_1n69yep') {
        flag = true
      } else {
        flag = false
      }
      if (this.detailType == 'check') {
        flag = true
      }
      return flag

    },
    cantRename3() {
      //不可编辑的条件
      //cantRename 为 true 为不可编辑
      let flag = false
      if (this.detailType == 'approve' && this.formBaseData.taskKey == 'UserTask_0yhw2t4' ||
        this.detailType == 'approve' && this.formBaseData.taskKey == 'UserTask_1g1pltw') {
        flag = false
      } else {
        flag = true
      }
      if (this.detailType == 'check') {
        flag = true
      }

      return flag

    },
    //字典--监督检查类型
    getDict() {
      this.inspectionTypeArr = []
      crudDict.getByCode('supervisory_inspection_type').then(res => {
        if (res.code == 200) {
          this.inspectionTypeArr = res.data
        }
      })
    },

    getAllCompanyTree(id) {
      return projectSectionInfo.getAllCompanyTree(id).then(res => {
        if (res.code === 200) {
          var data = res.data;
          this.companylist = data
          if (this.detailType == "build" && this.companylist.length > 0) {
            this.formBaseData.companyId = this.companylist[0].id
          }

          return new Promise(reslove => {
            reslove(res)
          })
          // this.$forceUpdate()
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2("获取项目标段树失败")
      })
    },
    getCompanyBySectionId() {
      sectionInfo.getCompanyBySectionId(this.formBaseData.sectionId).then(res => {
        if (res.status === 1) {
          var data = res.data
          this.formBaseData.buildUnit = data.buildUnit
          this.formBaseData.buildUnitId = data.buildUnitId
          this.inspectedCompanyList = [{ name: data.buildUnit, id: data.buildUnitId }]
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2('获取标段相关单位失败')
      })
    },

    checkoutArea() {
      let canApply = true
      this.formBaseData.items.forEach((item, index) => {
        if (item.hasOwnProperty('passStatus') && item.passStatus == '2' && item.hasOwnProperty('dutyArea') && item.dutyArea == '') {
          canApply = false
        }
        if (item.hasOwnProperty('passStatus') && item.passStatus == '2' && !item.hasOwnProperty('dutyArea')) {
          canApply = false
        }
      })
      return canApply
    },
    pOpen(row) {
      console.log(row, 'row')
      this.chooseRow = row
      this.showAreaSelectDialog = true
      this.$nextTick(() => {
        if (this.chooseRow.hasOwnProperty('ids')) {
          if (this.chooseRow.ids.indexOf(',') > -1 && this.chooseRow.ids.split(',').length > 0) {
            this.defaultCheckArr = this.chooseRow.ids.split(',')
          }
        } else {
          this.$set(this, 'defaultCheckArr', [])
        }

      })
    },
    clearRiskName(row) {
      row.dutyArea = ''
      this.subcontractCompanyName = ''
      setTimeout(() => {
        this.treePopover = false
      })
    },
    chooseTheseTree() {
      let getC = this.$refs.addTree.getCheckedNodes();
      this.chooseRow.dutyArea = (getC.map(it => it.areaName)).join(',')
      this.chooseRow.ids = (getC.map(it => it.id)).join(',')
      this.chooseRow.subcontractCompanyName = (getC.map(it => it.subcontractCompanyName)).join(',')
      console.log(this.chooseRow, 'chooseRow')
      this.showAreaSelectDialog = false

    },
    handleTreeNodeClick(data) {
      //  alert(JSON.stringify(data));
      // this.chooseRow.dutyArea = data.areaName
      // this.chooseRow.subcontractCompanyName=data.subcontractCompanyName
      // this.showAreaSelectDialog = false
    },
    needRectificationChange(value) {
      this.calculateNumberAndText()
      this.initBtn()
    },
    updateData(val, row) {
      // if(val == '1'){
      //
      // }
      this.calculateNumberAndText()
      this.$forceUpdate()
    },
    calculateNumberAndText() {
      let i = 0
      let str = ''
      let str2 = ''
      this.formBaseData.items.forEach((item, index) => {
        if (item.hasOwnProperty('passStatus') && item.passStatus == '2') {
          i++
          str = str + `${item.checkContent}(不通过)；`
          str2 = str2 + `${item.rectificationRequirements}；`
        }
      })
      this.$set(this.formBaseData, 'hiddenDangersNumber', i)
      this.$set(this.formBaseData, 'hiddenPartsAndDescribe', str)
      if (this.formBaseData.needRectification == '1') {
        if (str2 !== '；') {
          this.$set(this.formBaseData, 'suggestedRectificationMeasures', str2)
        }

      } else {
        this.$set(this.formBaseData, 'suggestedRectificationMeasures', '')
      }
    },
    removeRow(scope) {
      let that = this
      console.log(scope)
      console.log(this.formBaseData.items)
      this.$confirm('确定是否删除本数据？', '提示', {
        confirmButtonClass: 'iconfont icon-icon_ok',
        cancelButtonClass: 'iconfont icon-icon_cancel',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        //判断删除的数据 是子节点：
        // 1、如果有另外的同级子节点，则直接删除选中的节点 。
        // 2、如果是唯一子节点，需要找到其父级，如果父级也是同级唯一，往上递归，如果一直没出现同级有兄的，那就删光，否则就删除到出现同级的时候。
        //如果删除的是父节点
        //  大前提，先把子级全删掉，
        //公共删除子的递归
        let deleteSon = function (data) {
          let code = data.code
          // let parentCode = data.parentCode
          for (let i in that.formBaseData.items) {
            if (that.formBaseData.items[i].parentCode == code) {
              that.formBaseData.items[i].isNeedDelete = true
              deleteSon(that.formBaseData.items[i])
            }
          }
        }
        //删除孤寡节点，判断父级的递归
        let func = function (data) {
          let parentCode = data.parentCode
          let length = 0
          for (let i in that.formBaseData.items) {
            if (that.formBaseData.items[i].parentCode == parentCode) {
              length++
            }
          }
          if (length == 1) {
            for (let j in that.formBaseData.items) {
              if (that.formBaseData.items[j].code == parentCode) {
                that.formBaseData.items[j].isNeedDelete = true
                //删除该 孤寡父节点
                // 递归
                func(that.formBaseData.items[j])
              }
            }
          }
        }
        if (scope.row.hasOwnProperty('checkContent')) {
          let code = scope.row.code
          scope.row.isNeedDelete = true

          func(scope.row)
        } else {
          //删除的是父级，需要删除以它为父的所有子节点和他本身，并且判断它的父
          //如果是顶级
          if (!scope.row.hasOwnProperty('parentCode') || scope.row.parentCode == undefined) {
            scope.row.isNeedDelete = true
            deleteSon(scope.row)
          }
          //如果是中级
          if (scope.row.hasOwnProperty('parentCode') && scope.row.parentCode != undefined) {
            // //如果有父级节点 说明删除的是 中级节点，判断删除之后 判断 有同一父节点的中级节点数量，如果为0 就删除父节点，递归，再判断 父节点和其父父节点的数量关系
            scope.row.isNeedDelete = true
            func(scope.row)
            deleteSon(scope.row)
          }
        }
        //处理属性包含isNeedDelete = 数据
        this.formBaseData.items = this.formBaseData.items.filter(item => {
          if (!item.hasOwnProperty('isNeedDelete')) {
            return item
          }
        })
        //处理vxetable
        for (let i in this.vxeTableCheckData) {
          let flag = false
          for (let j in this.formBaseData.items) {
            if (this.formBaseData.items[j].code == this.vxeTableCheckData[i].code) {
              flag = true
            }
          }
          if (!flag) {
            this.vxeTableCheckData[i].isNeedDelete = true
          }
        }
        //处理属性包含isNeedDelete = 数据
        this.vxeTableCheckData = this.vxeTableCheckData.filter(item => {
          if (!item.hasOwnProperty('isNeedDelete')) {
            return item
          }
        })
      })
      this.$forceUpdate()
    },

    disabledFun({ row }) {
      return this.checkRowKeys.indexOf(row.id) < 0
    },
    selectChangeEvent({ $table }) {
      const records = $table.getCheckboxRecords()
      console.info(`勾选${records.length}个树形节点`, records)
      this.$set(this, 'vxeTableCheckData', records.filter(it => it.hasOwnProperty('checkContent')))

    },
    addNewFile(type) {
      if (type == 1) {
        let obj = {
          stuffName: '新增附件',
          part: `pcnr${this.tableLong++}`,
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true
        }
        this.buildUnitTable.push(obj)
        this.$forceUpdate()
      }
      if (type == 2) {
        let obj = {
          stuffName: '新增附件',
          part: `zghf${this.tableLong++}`,
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true
        }
        this.buildUnitTableTwo.push(obj)
        this.$forceUpdate()
      }
      if (type == 3) {

        let obj = {
          stuffName: '新增附件',
          part: `zgys${this.tableLong++}`,
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true
        }
        this.buildUnitTableThree.push(obj)
        console.log(this.buildUnitTableThree, 'buildUnitTableThree')
        this.$forceUpdate()
      }

    },
    funcActiveMethod() {

    },
    handleChange(val) {
      console.log(val)
      console.log(this.activeCollapse, 'activeCollapse')
    },
    delTableItem(val) {

    },
    getContentFunction(row) {
      return `${(row.hasOwnProperty('isContent') && row.isContent) ? row.content : row.type}`
    },
    closeDialogReset() {
      this.contractListTable = []
      this.showContractListDialog = false
    },
    handleSelectionChange(val) {
      console.log(val)
    },

    buildTree(data) {
      let map = {}
      data.forEach((node) => {
        map[node.id] = node
        node.children = []
      })
      let roots = []

      data.forEach((node) => {
        if (node.pid !== '0') {
          map[node.pid].children.push(node)
        } else {
          roots.push(node)
        }
      })
      return roots
    },
    selectworklist() {
      this.showContractListDialog = true
      this.$set(this, 'contractListTable', JSON.parse(JSON.stringify(this.matherData)))
      this.$nextTick(() => {
        this.$set(this, 'checkRowKeys', this.vxeTableCheckData.map(it => it.id))
        console.log(this.vxeTableCheckData, 'this.vxeTableCheckData')
        this.$set(this, 'checkRowKeysByName', this.vxeTableCheckData.map(it => it.id))
        console.log(this.checkRowKeys)
        this.$forceUpdate()
      })

    },
    changeTab(index) {
      this.activeIndex = index
    },
    showRowTable() {
      if (this.detailType == 'check' || this.detailType == 'approve') {
        return true
      } else {
        return false
      }
    },
    setPosition(val) {
      console.log(val, '获取的经纬度')
      this.$set(this.formBaseData, 'longitude', val.JD ? val.JD : '--')
      this.$set(this.formBaseData, 'latitude', val.WD ? val.WD : '--')
      this.$set(this.formBaseData, 'location', val.positionName ? val.positionName : '--')
    },
    showPicker() {
      this.showPickerObj = {
        show: true,
        projectId: this.search.projectId
      }
    },
    getInspectionLevel() {
      crudDict.getByCode('inspectionLevel').then(res => {
        if (res.code == 200) {
          this.inspectionLevelList = res.data
        }
      })
    },
    startChange(value, row) {
      this.startTimeOptions.disabledDate = time => {
        if (row) {
          if (time.getTime() > new Date(row).getTime()) {
            return true
          }
        }
        // if(time.getTime() > Date.now()){
        //   return true
        // }
      }
    },
    getPlanName() {
      this.$httpGet(`buss/checkPlan/getPlanName?sectionId=` + this.search.sectionId).then(res => {
        if (res.code === 200) {
          this.planNameArr = res.data
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch((res) => {
        console.log(res)
      }).finally((response) => {
      })
    },
    endChange(value, row) {
      this.endTimeOptions.disabledDate = time => {
        if (row) {
          if (time.getTime() < new Date(row).getTime()) {
            return true
          }
        }
        // if(time.getTime() > Date.now()){
        //   return true
        // }
      }
    },
    genReport(id) {
      this.$httpPost('/buss/supervisionCheck/genReport', {
        id: id
      }).then(res => {

        console.log(res)
      }).catch(res => {
        console.log(res)
      })
    },
    genReportReply(id) {
      this.$httpPost('/buss/qualitySafetyManagement/genReportReply', {
        id: id
      }).then(res => {

        console.log(res)
      }).catch(res => {
        console.log(res)
      })
    },
    changeSectionInfo() {
      //this.initBtn()
      this.formBaseData.constructionUnitName = ''
      this.formBaseData.supervisorUnitName = ''
      this.formBaseData.constructionUnitId = ''
      this.formBaseData.supervisorUnitId = ''
      sectionInfo.getCompanyBySectionId(this.formBaseData.sectionId).then(res => {
        if (res.status === 1) {
          var data = res.data
          this.formBaseData.constructionUnitName = data.buildUnit
          this.formBaseData.accountabilityUnit = data.buildUnit
          this.formBaseData.supervisorUnitName = data.supervisorUnit
          this.formBaseData.constructionUnitId = data.buildUnitId
          this.formBaseData.supervisorUnitId = data.supervisorUnitId

        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2('获取标段相关单位失败')
      })
    },
    onComplete(data) {
      this.wfNode = data
    },
    onApprove(params, callback) {
      if (this.checkedLinkUsers.length == 0) {
        msgUtil.error2('请选择检查人员!')
        callback && callback()
        return
      }
      let index = this.tabs.findIndex(e => e.id === 2)
      if (index !== -1) {
        if (!this.formBaseData.completionTime) {
          msgUtil.error2('请选择整改完成日期!')
          callback && callback()
          return
        }
        if (!this.formBaseData.projectSection) {
          msgUtil.error2('请填写项目名称!')
          callback && callback()
          return
        }
        if (!this.formBaseData.accountabilityUnit) {
          msgUtil.error2('请填写责任单位!')
          callback && callback()
          return
        }
        if (!this.formBaseData.rectificationResult) {
          msgUtil.error2('请填写整改结果!')
          callback && callback()
          return
        }
      }
      this.formBaseData.inspector = this.checkedLinkUsers
      const dealForm = this.$refs.bpmnForm.getForm()
      this.approveForm.procDefKey = 'supervisionCheckProcess'
      this.approveForm.businessId = this.formBaseData.id
      this.approveForm.procInstId = this.formBaseData.procInstId
      this.approveForm.description = dealForm.description
      this.approveForm.hiddenPartsAndDescribe = dealForm.hiddenPartsAndDescribe
      this.approveForm.selectAssigneeList = dealForm.selectAssigneeList
      if (Array.isArray(this.formBaseData.checkQuestionType)) {
        this.formBaseData.checkQuestionType = this.formBaseData.checkQuestionType.join(",")
      }
      if (Array.isArray(this.formBaseData.worksCategory)) {
        this.formBaseData.worksCategory = this.formBaseData.worksCategory.join(",")
      }
      this.approveForm.entity = this.formBaseData
      this.approveForm.problem = this.formBaseData.needRectification
      // 覆盖按钮参数
      Object.assign(this.approveForm, params)
      if (!params || params.isReject != 1) {
        if (this.$refs.bpmnForm.showUserSelect) {
          if (!dealForm.selectAssigneeList.length) {
            msgUtil.error2('请选择处理人!')
            callback && callback();
            return
          }
        }
      }
      supervisionCheck.audit(this.approveForm).then(r => {
        this.detailId = this.formBaseData.id
        this.saveFiles()
        this.genReport(this.formBaseData.id)
        // this.genReportReply(this.formBaseData.id)
        msgUtil.success2('审批成功!')
        this.formShow = false
        this.$emit('reloadList')
      }).finally(() => {
        callback && callback()
      })
    },
    onApply(_, callback) {
      const dealForm = this.$refs.bpmnForm.getForm()
      if (!dealForm.selectAssigneeList.length) {
        msgUtil.error2('请选择处理人!')
        callback && callback()
        return
      }
      if (this.checkedLinkUsers.length == 0) {
        msgUtil.error2('请选择检查人员!')
        return
      }
      this.formBaseData.inspector = this.checkedLinkUsers
      let startForm = {}
      this.formBaseData.buildUnit = this.inspectedCompanyList.find(item => item.id === this.formBaseData.buildUnitId).name
      startForm.entity = this.formBaseData
      startForm.procDefKey = 'supervisionCheckProcess'
      startForm.businessId = this.formBaseData.id
      startForm.variables = this.variables
      startForm.selectAssigneeList = dealForm.selectAssigneeList
      this.$refs['formBaseData'].validate(async (valid) => {
        if (valid) {
          await getRoleByUserId(startForm.selectAssigneeList[0]).then(res => {
            if (res.data.findIndex(item => item === 'ff8080818bff58ff018c33a8d87a05a2') > -1) {
              startForm.variables.principal = 2
            } else {
              startForm.variables.principal = 1;
            }
          });
          supervisionCheck.report(startForm).then(r => {
            if (r.code == 200) {
              this.detailId = r.data.businessId
              this.saveFiles()
              this.genReport(r.data.businessId)
              this.formShow = false
              setTimeout(() => {
                this.$emit('reloadList')
              }, 500);
              this.$notify({
                title: '上报成功',
                type: 'success',
                duration: 1500
              })
            }
          }).finally(() => {
            callback && callback()
          })
        } else {
          callback && callback()
        }
      })
    },
    cancel() {
      this.handleClickDeal('cancel')
    },
    onSave(_, callback) {
      this.submitAudit(callback)
    },
    initBtn() {
      const params = {
        businessId: this.formBaseData.id,
        procDefKey: 'supervisionCheckProcess',
        url: this.url,
        entity: this.formBaseData,
        variables: this.variables,
      }
      params.variables.problem = this.formBaseData.needRectification
      this.$refs.bpmnForm && this.$refs.bpmnForm.initNodeAttribute(params)
      this.$refs.btn && this.$refs.btn.getBtnListWithParam(params)
    },
    initData() {
      this.companyTree = []
      projectSectionInfo.getProjectSectionInfoTree().then(res => {
        if (res.code === 200) {
          var data = res.data
          this.companyTree = data

          if (this.detailType == 'build' && this.companyTree.length > 0) {
            this.formBaseData.companyId = this.companyTree[0].id
            this.getProjectByCompanyId()
          } else {
            this.getProjectByCompanyId()
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch((e) => {
        console.log(e)
        msgUtil.error2('获取项目标段树失败')
      })

    },
    /**
     *  根据建设单位查询下面的所有项目
     * */
    getProjectByCompanyId() {
      this.companyTree.forEach((item) => {
        // if (item.id === this.formBaseData.companyId) {
        this.projectTree = item.children
        if (this.detailType == 'build' && this.projectTree.length > 0) {

          this.formBaseData.projectId = this.projectTree[0].id
          this.formBaseData.projectName = this.projectTree[0].name
          this.getSectionByProjectId()
        } else {
          this.getSectionByProjectId()
        }
        // }
      })
    },

    /**
     * 根据项目id获取标段列表
     * getContractByProjectId
     * */
    getSectionByProjectId() {

      if (this.formBaseData.sectionId && !this.checkInitShow) {
        this.formBaseData.sectionId = ''
      }

      if (this.checkInitShow) {
        this.checkInitShow = false
      }

      if (this.formBaseData.projectId) {
        this.projectTree.forEach((item) => {
          if (item.id == this.formBaseData.projectId) {
            this.sectionTree = item.children
            if (this.detailType == 'build' && this.sectionTree.length > 0) {
              this.formBaseData.sectionId = this.sectionTree[0].id
              this.formBaseData.sectionName = this.sectionTree[0].name
              this.changeSectionInfo()
            }
          }
        })
      }
    },

    /**
     * 重置主表数据
     * */
    resetFormData() {
      this.formBaseData = {
        user: {},
        initiator: 1,
        needRectification: '2',
        hiddenPartsAndDescribe: '',
        hiddenDangersNumber: '',
        projectName: '',
        sectionName: '',
        inspector: '',
        checkPlan: '',
        checkOption: '',
        inspectionTime: '',
        inspectionLevel: '',
        longitude: '',
        latitude: '',
        suggestedRectificationMeasures: '',
        rectificationDeadline: '',
        hiddenInformation: '',
        projectId: '',
        sectionId: '',
        rectificationMeasures: '',
        rectificationStartDate: '',
        rectificationCompletionDate: '',
        headRectification: '',
        acceptanceCondition: '',
        //  标题
        title: '',
        rectificationDate: '',
        isAuditUpdate: 0,
        opinion: '',
        checkUser: '',
        checkDate: '',
        checkUnit: '',
        isRectification: '2',
        isNotice: '2',
        problemType: '',
        urgency: '',
        lon: '',
        lat: '',
        location: '',
        locationAll: '',
        checkTime: '',
        items: [],
        fileStr: {},
        note: '',
        noticeNum: '',
        dateIssue: '',
        checkQuestionType: '',
        worksCategory: '',
        categoryName: '',
        parts: '',
        existingProblems: '',
        headPerson: '',
        replyCode: '',
        zghf: true,
        zgys: true
      }
      this.taskDefKey = ''
      this.entityId = ''
    },

    /***
     * 提交保存数据
     * */
    submit(flag, callback) {
      let url = this.url.submit
      if (this.detailType !== 'build') {
        url = this.url.resubmit
      }

      if (this.taskDefKey != null && this.taskDefKey != undefined && this.taskDefKey != '') {
        this.formBaseData.isAuditUpdate = 1
      }
      if (this.taskDefKey == null || this.taskDefKey == undefined || this.taskDefKey == '') {
        this.formBaseData.isAuditUpdate = 0
      }
      this.formBaseData.contractId = this.contractId
      this.$httpPost(url, this.formBaseData).then(res => {
        if (res.data.status === 1) {
          this.$messageSuccess('保存成功')
          this.formShow = false
          this.detailId = res.data.id
          this.isLoading = false
          if (callback) callback(res.data)
        } else {
          this.isLoading = false
          this.$messageError(res.data.message)
        }
      }).catch(e => {
        console.log('请求出现错误', e)
        this.isLoading = false
        console.log('提交失败', e)
        this.$messageError('请求失败')
      })
    },
    /**
     * 获取详情并整理数据
     * */
    getDetail() {
      supervisionCheck.getOne(this.detailBaseId).then(res => {
        if (res.code == 200) {
          let data = res.data
          let arr = [{ name: '检查内容', id: 0 }];
          this.formBaseData = data
          if (['UserTask_1sci9cl', 'UserTask_0t9gy8c', 'UserTask_0bm9j9l', 'UserTask_1aroths', 'end'].indexOf(this.formBaseData.taskKey) !== -1) {
            arr.push({ name: '整改回复', id: 2 })
            this.changeSectionInfo()
          }
          this.$set(this, 'tabs', arr)
          this.getZghf()
          // 审批情况下，如果整改回复是编辑状态，就切换到这个页
          if (this.detailType == 'approve') {
            if (!this.formBaseData.zghf) {
              this.activeIndex = 2
            }
          }
          this.checkedLinkUsers = JSON.parse(this.formBaseData.inspector)
          this.getCompanyBySectionId()
          this.getProjectByCompanyId()
          this.formBaseData.projectSection = data.projectName + " " + data.sectionName
          if (this.detailType == 'approve' || this.detailType == 'edit') {
            this.initBtn()
          }
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(() => {
        msgUtil.error2('获取详情信息失败')
      })
    },
    /**
     * 审批提交成功的回调函数
     * */
    onAuditSubmitSuccess() {
      //  关闭查看框并刷新列表
      this.formShow = false
      this.$emit('reloadList')
    },
    /**
     * 选中流程动作选项时的回调函数
     * */
    onSeledAuditAction() {
      this.showAuditBtn = true
    },

    submitAudit(callback) {
      this.$refs['formBaseData'].validate((valid) => {
        if (valid) {
          if (this.detailType === 'build') {
            supervisionCheck.submit(this.formBaseData).then(res => {
              if (res.code === 200) {
                this.detailId = res.data.id
                console.log(this.detailId)
                this.saveFiles()
                this.genReport(res.data.id)
                this.formShow = false
                this.$emit('reloadList')
                this.$notify({
                  title: '监督检查保存成功',
                  type: 'success',
                  duration: 1500
                })
              } else {
                msgUtil.error2(res.data.message)
              }
            }).catch((response) => {
              console.log(response)
              this.$notify({
                title: '质量检查保存失败',
                type: 'error',
                duration: 2500
              })
            }).finally((response) => {
              callback && callback()
            })
          } else {
            /* if(Array.isArray(this.formBaseData.checkQuestionType)){
               this.formBaseData.checkQuestionType=this.formBaseData.checkQuestionType.join(",")
             }
             if(Array.isArray(this.formBaseData.worksCategory)){
               this.formBaseData.worksCategory=this.formBaseData.worksCategory.join(",")
             }*/
            supervisionCheck.resubmit(this.formBaseData).then(res => {
              if (res.code === 200) {
                this.detailId = res.data.id
                console.log(this.detailId)
                this.saveFiles()
                this.genReport(res.data.id)
                // 传值给父组件刷新列表
                this.$notify({
                  title: '数据修改成功',
                  type: 'success',
                  duration: 1500
                })
                this.$emit('reloadList')
                this.formShow = false
              } else {
                msgUtil.error2(res.data.message)
              }
            }).catch((response) => {
              this.$notify({
                title: '数据修改失败',
                type: 'error',
                duration: 2500
              })
            }).finally((response) => {
              callback && callback()
            })
          }
        } else {
          callback && callback()
        }
      })
    },
    saveFiles() {
      for (let k in this.fileSystem) {
        let fileProp = this.fileSystem[k]
        if (this.$refs[fileProp.compoName]) {
          this.$refs[fileProp.compoName].saveAll(this.detailId)
        }
      }
    },

    /**
     * 控制上传按钮显示
     * @param row
     * @returns {boolean}
     */
    buttonUploadShow(row) {
      let flag = false

      if (this.detailType === 'build' || this.detailType === 'edit') {
        flag = true
      }
      return flag
    },
    buttonUploadShow2(row) {
      let flag = false
      if ((this.detailType === 'approve' && (this.formBaseData.taskKey == 'UserTask_1n69yep' || this.formBaseData.taskKey == 'UserTask_1i38bv8'))) {
        flag = true
      } else {
        flag = false
      }
      return flag
    },
    buttonUploadShow3(row) {
      let flag = false
      if ((this.detailType === 'approve' && this.formBaseData.taskKey == 'UserTask_079jyn1')
        || (this.detailType === 'approve' && this.formBaseData.taskKey == 'UserTask_0yhw2t4')
        || (this.detailType === 'approve' && this.formBaseData.taskKey == 'UserTask_168mko6')) {
        flag = true
      }
      return flag
    },
    /**
     * 控制查看按钮显示
     * @param row
     */
    buttonCheckShow(row) {
      let flag = false
      if (
        this.detailType !== 'build' &&
        this.detailType !== 'edit' &&
        row.file[0].realName !== ''
      ) {
        flag = true
      }
      // 多文件上传的控制的控制
      if (row.isMulti) {
        flag = false
      }
      return flag
    },
    /**
     *控制显示暂无文件
     * @param row
     */
    showNone(row) {
      let flag = false
      if (
        this.detailType !== 'build' &&
        this.detailType !== 'edit' &&
        row.file[0].realName === ''
      ) {
        flag = true
      }
      if (this.detailType === 'approve' && this.formBaseData.taskKey == 'UserTask_1n69yep') {
        if (row.stuffName == '整改单位附件') {
          flag = false
        }
      }
      return flag
    },
    showNone2(row) {
      let flag = false
      if (
        this.detailType !== 'build' &&
        this.detailType !== 'edit' &&
        row.file[0].realName === ''
      ) {
        flag = true
      }
      if (this.detailType === 'approve' && row.file[0].realName === '') {
        flag = false
      }

      return flag
    },
    showNone3(row) {
      let flag = false
      if (
        this.detailType !== 'build' &&
        this.detailType !== 'edit' &&
        row.file[0].realName === ''
      ) {
        flag = true
      }
      if (this.detailType === 'approve' && row.file[0].realName === '') {
        flag = false
      }
      if (this.detailType === 'approve' && this.formBaseData.taskKey == 'UserTask_0t9gy8c') {
        flag = false
      }
      return flag
    },
    /**
     *显示删除按钮
     * @param row
     */
    buttonDelShow(row) {
      let flag = false
      if (
        (this.detailType === 'build' || this.detailType === 'edit') &&
        row.file[0].realName !== '' &&
        !row.isNeed
      ) {
        flag = true
      }
      // 多文件上传的控制的控制
      if (row.isMulti) {
        flag = false
      }
      return flag
    },
    ////////////////////////////////以上是附件上传所需代码

    tableChange(val, type) {
      if (type == 'cmsFileTable_one') {
        this.$set(this, 'buildUnitTable', [...val])

      }
      if (type == 'cmsFileTable_Two') {
        this.$set(this, 'buildUnitTableTwo', [...val])

      }
      if (type == 'cmsFileTable_Three') {
        this.$set(this, 'buildUnitTableThree', [...val])

      }
    },
    addList() {
      //调接口
      //打开dialog
      this.showSelectDialog = true
    },
    handleClick(activeName) {
      console.log(activeName)
    },
    // 事件处理的api请求
    sealDealHttp(url, query, params, callback) {
      this.$httpPost(
        this.$store.state.httpHost.buss + url + query,
        params
      ).then(res => {
        if (res.data.status === 1) {
          if (callback) callback(res.data)
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(res => {
        console.log(res)
      })
    },
    handleTreeData(treeData) {
      if (!treeData || treeData.length === 0) {
        return []
      }
      const array = []
      for (let i = 0; i < treeData.length; i += 1) {
        let match = false
        if (treeData[i].hasOwnProperty('isSelect') && treeData[i].isSelect != false) {
          match |= (treeData[i].hasOwnProperty('isSelect'))
          if (!match) break
        }
        if (this.handleTreeData(treeData[i].children).length > 0 || match) {
          console.log(treeData[i], 'cccccccc')
          array.push({
            ...treeData[i],
            children: this.handleTreeData(treeData[i].children)
          })
        }
      }
      return array
    },
    // 点击各个流程的按钮事件
    handleClickDeal(type, res) {
      console.log(type, res)
      switch (type) {
        // 取消，关闭窗口
        case 'cancel':
          // 重置表单验证
          this.$refs['formBaseData'].resetFields()
          this.$set(this, 'checkRowKeys', [])
          this.$set(this, 'vxeTableCheckData', [])
          this.$set(this, 'contractListTable', [])
          this.activeCollapse = ['1', '2']
          this.activeCollapseTwo = ['3']
          this.activeCollapseThree = ['4']
          this.variables = { principal: 3 }
          this.showContractListDialog = false
          this.areaList = []
          this.selectedIds = []
          this.activeIndex = 0
          this.buildUnitTable = []
          this.buildUnitTableTwo = []
          this.buildUnitTableThree = []
          this.formBaseData.needRectification = '2'
          this.activeIndex = 0
          // 清空表单内容
          this.resetFormData()
          this.fileList = []
          this.fileList1 = []
          if (this.$refs.bpmnForm && this.$refs.bpmnForm.form.selectAssigneeList) {
            this.$refs.bpmnForm.form.selectAssigneeList = []
          }
          if (this.$refs.bpmnForm && this.$refs.bpmnForm.form.hiddenPartsAndDescribe) {
            this.$refs.bpmnForm.form.hiddenPartsAndDescribe = ''
          }
          this.detailId = ''
          this.detailBaseId = ''
          this.isShowBpmn = false
          // 关闭弹窗
          this.formShow = false
          this.checkedLinkUsers = []
          break
        // 保存
        case 'submit':
          let flag = res.flag
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              // 再验证其他内容
              // 整理文件信息
              this.isLoading = true
              // 提交详情

              this.submitDetail(flag, () => {
                this.saveFiles()
                this.isLoading = false
                // 传值给父组件刷新列表
                this.$emit('reloadList')
                this.$notify({
                  title: '项目自检保存成功',
                  type: 'success',
                  duration: 1500
                })
              })
            }
          })
          break
        case 'selected':

          break
        case 'selectedcancel':
          let arr = []
          this.vxeTableCheckData.forEach((item, index) => {
            if (this.checkRowKeys.indexOf(item.id) > -1) {
              arr.push(item)
            }
          })
          this.$set(this, 'vxeTableCheckData', arr)
          //vxeTableCheckData 是勾选的所有数据，包括 新的和旧的，
          this.showContractListDialog = false
      }
    },
    findFatherById(ids, alReadyId) {
      let that = this
      console.log(ids, '缺少的father code')
      let fatherArr = []
      let bianpingArr = []

      let func = function (list) {
        let res = []
        res = list.concat(...list.map(item => {
          if (item.childList instanceof Array && item.childList.length > 0 && !item.childList[0].hasOwnProperty('checkContent')) {
            return func(item.childList)
          }
          return null
        }).filter(o => o instanceof Array && o.length > 0))
        return res
      }
      bianpingArr = func(this.contractListTable)

      console.log(bianpingArr)
      let fun = function (code) {
        let itemCodes = that.formBaseData.items.map(it => it.code)
        for (let j in bianpingArr) {
          if (bianpingArr[j].code == code && !itemCodes.includes(code)) {
            that.formBaseData.items.push(bianpingArr[j])
            if (bianpingArr[j].hasOwnProperty('parentCode')) {
              //递归下一次
              fun(bianpingArr[j].parentCode)
            } else {
              continue
            }
          }
        }
      }
      for (let i in ids) {
        for (let j in bianpingArr) {
          if (ids[i] == bianpingArr[j].code) {
            if (!alReadyId.includes(ids[i])) {
              this.formBaseData.items.push(bianpingArr[j])
            }
            if (bianpingArr[j].hasOwnProperty('parentCode') && !alReadyId.includes(bianpingArr[j].parentCode)) {
              let isHave = false
              for (let t in this.formBaseData.items) {
                if (this.formBaseData.items[t].code == bianpingArr[j].parentCode) {
                  isHave = true
                }
              }
              if (isHave == false) {
                fun(bianpingArr[j].parentCode)
              }
            }
          }
        }
      }
    },

    //获取发起人所在公司人员树
    getApplyCompany() {
      let type = 2;
      if (this.detailType) {
        if (this.detailType === 'build' || this.detailType === 'edit') {
          type = 1
        }
      }
      return supervisionCheck.getApplyCompany(type).then(res => {
        if (res.code === 200) {
          this.linkUserOpts = res.data;
          // console.log("数据：", this.linkUserOpts)
          this.collectDeptUserById(res.data);
          this.collectDeptUserCompById(res.data);
          this.$forceUpdate();
        } else {
          msgUtil.error2(res.data.message)
        }
      }).catch(res => {
        console.log('请求出现错误', res);
        msgUtil.error2('获取部门用户列表失败!')
      })
    },
    /**
     *  -----@addMulTag="addMulTag"
     * 多选增加--多选模式使用
     * @param val
     */
    addMulTag(val) {
      console.log(val)
      this.checkedLinkUsers = []
      val.forEach((item) => {
        this.checkedLinkUsers.push(item)
      })
      this.$forceUpdate()
    },
    addMulTag0(val) {
      this.checkedownerRepresentativeUsers.splice(0, this.checkedownerRepresentativeUsers.length)
      val.forEach((item) => {
        this.checkedownerRepresentativeUsers.push(item)
      })
    },
    /**
     * 删除会签部门人
     */
    delTag(val) {
      this.checkedLinkUsers.splice(val, 1)
      this.$forceUpdate()
      this.$refs.cmsPopoverTree.updateTree()
      this.$refs.cmsPopoverTree.$forceUpdate()
    },
    delTag0(val) {
      this.checkedownerRepresentativeUsers.splice(val, 1)
      this.$forceUpdate()
      this.$refs.cmsPopoverTree.updateTree()
      this.$refs.cmsPopoverTree.$forceUpdate()
    },
    /**
     * 增加会签人
     * @param val
     */
    addTag(val) {
      this.checkedLinkUsers.push(val)
      this.$refs.cmsPopoverTree.updateTree()
      this.$refs.cmsPopoverTree.$forceUpdate()
      this.$forceUpdate()
      console.log("checkedLinkUsers=", this.checkedLinkUsers)
    },
    addTag0(val) {
      this.checkedownerRepresentativeUsers.push(val)
      this.$refs.cmsPopoverTree0.updateTree()
      this.$refs.cmsPopoverTree0.$forceUpdate()
      this.$forceUpdate()
    },

    collectDeptUserById(linkUserOpts) {
      for (let i = 0; i < linkUserOpts.length; i++) {
        let user = linkUserOpts[i]
        let id = user.id
        let children = user.children
        this.linkUsers[id] = user
        if (children && children.length > 0) {
          this.collectDeptUserById(children)
        }
      }
    },

    collectDeptUserCompById(ownerRepresentativeUserOpts) {
      for (let i = 0; i < ownerRepresentativeUserOpts.length; i++) {
        let user = ownerRepresentativeUserOpts[i]
        let id = user.id
        let children = user.children
        this.ownerRepresentativeUsers[id] = user
        if (children && children.length > 0) {
          this.collectDeptUserCompById(children)
        }
      }
    },
  }
}
</script>

<style scoped lang="scss">
.fee_add {
  color: #008fe0;
  border-color: #008fe0;
  float: right;
  margin-bottom: 10px;
}

.el-input__inner {
  width: 291px;
}

.secondPanTop {
  .el-button--primary {
    color: #409eff;
    background-color: #ffffff;
    font-size: 13px;
    padding: 10px 5px;
  }
}

.flex {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.flex-center {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.dialogTableDiv {
  width: 100%;
  margin: 0 auto;

  .tableTitle {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;

    p {
      font-size: 16px;
    }

    .add {
      background-color: #ffffff;
      color: rgb(73, 163, 250);
    }
  }
}

.meterage-manage-detail
  .el-date-editor.el-input.el-input--prefix.el-input--suffix.el-date-editor--date {
  width: 255px;
}

.flex-row-center {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.content-box {
  border: 1px solid #e2e8ec;
  min-height: 500px;
  margin-top: 20px;
  display: flex;
  flex-direction: row;

  .left-box {
    border-right: 1px solid #e2e8ec;
    padding: 20px 0px 0px 40px;
    width: 200px;
    min-height: 100%;

    p {
      cursor: pointer;
      font-size: 15px;
    }

    .active {
      color: #409eff;
      font-weight: bold;
    }
  }

  .right-box {
    width: calc(100% - 200px);
    height: 100%;
    padding: 20px 20px;

    .text-link {
      cursor: pointer;
      color: #409eff !important;

      &:hover {
        text-decoration: underline;
      }
    }

    .text-link-split {
      color: #409eff !important;
    }

    .form-input {
      width: 100%;
    }

    .question-box {
      height: 300px;
      border-bottom: 1px solid #e2e8ec;
      // border-top: 1px solid #e2e8ec;
      display: flex;

      .question-left-box {
        border-right: 1px solid #e2e8ec;
        padding: 20px 5px;
        width: 140px;
        height: 100%;
        display: flex;
        flex-direction: column;

        .question-left-item {
          margin-bottom: 10px;
          display: flex;
          justify-content: space-between;
          align-items: center;

          span,
          i {
            cursor: pointer;
            font-size: 15px;
          }
        }

        .active {
          span {
            color: #409eff;
            font-weight: bold;
          }
        }

        .add-question {
          margin-top: auto;
          border: 1px solid #409eff !important;
          color: #409eff !important;
          background-color: transparent !important;
        }
      }

      .question-right-box {
        width: calc(100% - 140px);
        height: 100%;
        padding-left: 10px;
      }
    }
  }
}

.flex-align-center {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}

.changecost_contract_list {
  margin: 25px;

  .head {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;

    .headLeft {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
<style lang="scss">
.el-message-box {
  .el-message-box__btns {
    .el-button {
      font-size: 14px;
    }
  }
}
</style>

